const path = require('path')
const fs = require('fs')
const c = require('colors')

const componentDir = '../src/components'

const commonComponentDir = '../src/components/common/'

const filenames = fs.readdirSync(path.join(__dirname, componentDir))

const defaultComp = process.argv.pop()

console.log(defaultComp)

const classNames = []

let commonClassNames = []

for (let name of filenames) {
  if (name !== 'common' && name !== 'index') {
    const file = fs.readdirSync(path.join(__dirname, `${componentDir}/${name}`)).filter(f => f.split('.').pop() === 'tsx')[0].replace(".tsx", "")
    const className = file[0].toUpperCase() + file.slice(1)
    classNames.push(className)
  } else {
    commonClassNames = fs.readdirSync(path.join(__dirname, commonComponentDir)).map((n) => {
      return n[0].toUpperCase() + n.slice(1)
    })
  }
}


const genImport = (name, common) => {
  const n = name[0].toLowerCase() + name.slice(1);
  if (common) {
    return `
import { ${name}Props } from '@components/common/${n}/${n}'`
  }
  return `
import { ${name}Props } from '@components/${n}/${n}'`
}

let importText = ''

const genImportTextBlock = (list, common) => {
  const length = list.length
  for (let i = 0; i < length; i++) {
    const c = list[i]
    importText = importText + genImport(c, common)
  }
}

genImportTextBlock(commonClassNames, 'common')
genImportTextBlock(classNames)

genRoute = (name, common) => {
  const n = name[0].toLowerCase() + name.slice(1);
  let p = `@components/${n}/${n}`
  let m = name
  if (common) {
    p = `@components/common/${n}/${n}`
  }
  console.log(c.green('defaultComp: ', defaultComp))
  console.log(c.green('n: ', n))
  console.log(c.green(name))
  if (defaultComp === n ||
    new Set(['StudentDetail', 'StudentList', 'AsideMenu', 'Login', 'CreateStudentPage', 'CreateSubjectPage']).has(name)) {
    m = 'default'
  }

  return `
export const ${name}Component = Loadable({
  loader: () => {
    return import(/* webpackChunkName: "${n}" */ '${p}')
  },
  loading: (props: any) => Loading(props),
  render: (loaded, props: ${name}Props) => {
    return <loaded.${m} {...props} />
  }
})\n
`
}

let routeText = ''

const genRouteTextBlock = (list, common) => {
  const length = list.length
  for (let i = 0; i < length; i++) {
    const c = list[i]
    routeText = routeText + '\n' + genRoute(c, common)
  }
}

genRouteTextBlock(commonClassNames, 'common')
genRouteTextBlock(classNames)


const reuslt = `
/* Auto generated file, DO NOT edit by hand */
import * as React from 'react'
import * as Loadable from 'react-loadable'
${importText}
import { Loading } from '@components/common/loading/loading'
\n

// NOTE: 这里声明路由表
${routeText}\n
\n

`

fs.writeFileSync(path.join(__dirname, '../src', 'routeTables.tsx'), reuslt)


